package frame.security.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

//import org.codehaus.jackson.JsonParser;
//import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.support.json.JSONParser;
import com.alibaba.fastjson.JSON;

import frame.common.BaseService;
import frame.common.ConstantEntity;
import frame.common.Message;
import frame.dao.Page;
import frame.security.entity.AccessLog;
import frame.security.entity.Code;
import frame.security.entity.CodeType;
import frame.security.entity.Group;
import frame.security.entity.GroupPermit;
import frame.security.entity.Permisson;
import frame.security.entity.Resource;
import frame.security.entity.Role;
import frame.security.entity.RolePermit;
import frame.security.entity.User;

/**
 * frame的权限控制逻辑都是通过这个Controller实现的。这里面的一个方法对应前端的一个请求。
 * 基本上是些增删改查的方法。
 * warn:按照bean的定义规则，为dao指定使用那些字段的定义必须用小写 
 * 如：String[] order={"role_name","valid_flag"};
 * 而不是：String[] order={"ROLE_NAME","VALID_FLAG"};
 * @author MR.CUIPENG
 *
 */
@Controller
@RequestMapping("/mgr")
@SuppressWarnings("all")
public class FrameMgr extends BaseService{
	

	private static final long serialVersionUID = 4457520979277393165L;

	@RequestMapping(value = "/roles", method = RequestMethod.POST)
	@ResponseBody 
	public Page<Role> getRoles(int start,int size,String sort,String sortDirection){
		Page<Role> roles=dao.paginate(Role.class, "roles", start, size,sort,sortDirection, null);
		return roles;
	}
	
	@RequestMapping(value = "/addRole", method = RequestMethod.POST)
	@ResponseBody
	public Message addRoles(@Valid Role role,BindingResult result){
		String[] order={"role_name","valid_flag"};
		System.out.println(role);
		int  row=dao.updateObject("addrole", role, order);
		return Message.ADD_OK;
	}
	
	@RequestMapping(value = "/editRole", method = RequestMethod.POST)
	@ResponseBody
	public Message editRoles(Role role){
		String[] order={"role_name","valid_flag","role_id"};
		int  row=dao.updateObject("editrole", role, order);
		return Message.EDIT_OK;
	}
	
	@RequestMapping(value = "/delRole", method = RequestMethod.POST)
	@ResponseBody
	public Message deleteRoles(String role){
		dao.update("delrole", role);
		dao.update("delURole",role);
		dao.update("delARole",role);
		return Message.DEL_OK;
	}
	
	@RequestMapping(value = "/groups", method = RequestMethod.POST)
	@ResponseBody
	public Page<Group> getGroups(int start,int size,String sort,String sortDirection){
		Page<Group> groups=dao.paginate(Group.class, "groups", start, size,sort,sortDirection, null);
		return groups;
	}
	@RequestMapping(value = "/addGroups", method = RequestMethod.POST)
	@ResponseBody
	public Message addGroups(@Valid Group group,BindingResult result){
		String[] order={"group_name","valid_flag"};
		int  row=dao.updateObject("addgroup", group, order);
		return Message.ADD_OK;
	}
	@RequestMapping(value = "/editGroups", method = RequestMethod.POST)
	@ResponseBody
	public Message editGroups(Group group){
		String[] order={"group_name","valid_flag","group_id"};
		int  row=dao.updateObject("eidtgroup", group, order);
		return Message.DEL_OK;
	}
	@RequestMapping(value = "/delGroups", method = RequestMethod.POST)
	@ResponseBody
	public Message delGroups(String group_id){
		dao.update("delgroup", group_id);
		dao.update("delUGroup", group_id);
		dao.update("delAGroup", group_id);
		return Message.DEL_OK;
	}
	
	@RequestMapping(value = "/resources", method = RequestMethod.POST)
	@ResponseBody
	public Page<Resource> getResources(int start,int size,String sort,String sortDirection,String query){
		Resource res=JSON.parseObject(query, Resource.class);
		Page<Resource> resource=dao.paginate(Resource.class, res.select(), start, size,sort,sortDirection, res.args());
		return resource;
	}
	
	@RequestMapping(value = "/addResources", method = RequestMethod.POST)
	@ResponseBody
	public Message addResources(@Valid Resource resource,BindingResult result){
		String[] order={"uri","f_name","valid_flag","description"};
		int  row=dao.updateObject("addresources", resource, order);
		return Message.ADD_OK;
	}
	@RequestMapping(value = "/editResources", method = RequestMethod.POST)
	@ResponseBody
	public Message editResources(Resource resource){
		String[] order={"f_name","valid_flag","description","uri"};
		int  row=dao.updateObject("editresources", resource, order);
		return Message.DEL_OK;
	}
	@RequestMapping(value = "/delResources", method = RequestMethod.POST)
	@ResponseBody
	public Message delResources(String resource_id){
		dao.update("delresources", resource_id);
		dao.update("delAResource", resource_id);
		return Message.DEL_OK;
	}
	
	@RequestMapping(value = "/getPermitRoles", method = RequestMethod.POST)
	@ResponseBody
	public Page<RolePermit> getPermitRoles(int start,int size,String sort,String sortDirection,String u){
		Page<RolePermit> rolePermits=dao.paginate(RolePermit.class, "permitRoles", start, size,sort,sortDirection, u);
		return rolePermits;
	}
	@RequestMapping(value = "/getPermitGroups", method = RequestMethod.POST)
	@ResponseBody
	public Page<GroupPermit> getPermitGroups(int start,int size,String sort,String sortDirection,String u){
		Page<GroupPermit> groupPermits=dao.paginate(GroupPermit.class, "permitGroups", start, size,sort,sortDirection, u);
		return groupPermits;
	}
	
	@RequestMapping(value = "/updatePermitRoles", method = RequestMethod.POST)
	@ResponseBody
	public Message updatePermitRoles(@RequestBody Permisson per){
		List<Map<String,Object>> argsAdd=new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> argsDel=new ArrayList<Map<String,Object>>();
		//参数装配过程
		for (RolePermit rp : per.getRoles()) {
			Map<String,Object> arg=new HashMap<String, Object>();
			if("N".equals(rp.getPermit())){//如果该角色没有被授权，则插入到授权表中
				arg.put("uri", per.getUri());
				arg.put("rg_id", rp.getRole_id());
				arg.put("rg", "R");
				argsAdd.add(arg);
			}else{//如果该角色已经被授权，则从授权表中删除
				arg.put("uri", per.getUri());
				arg.put("rg_id", rp.getRole_id());
				arg.put("rg", "R");
				argsDel.add(arg);
			}
		}		
		String[] order={"uri","rg_id","rg"};
		dao.updateMaps("addPermits", argsAdd, order);
		dao.updateMaps("delPermits", argsDel, order);
		return Message.OK;
	}
	@RequestMapping(value = "/updatePermitGroups", method = RequestMethod.POST)
	@ResponseBody//
	public Message updatePermitGroups(@RequestBody Permisson per){
		List<Map<String,Object>> argsAdd=new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> argsDel=new ArrayList<Map<String,Object>>();
		//参数装配过程
		for (GroupPermit rp : per.getGroups()) {
			Map<String,Object> arg=new HashMap<String, Object>();
			if("N".equals(rp.getPermit())){//如果该角色没有被授权，则插入到授权表中
				arg.put("uri", per.getUri());
				arg.put("rg_id", rp.getGroup_id());
				arg.put("rg", "G");
				argsAdd.add(arg);
			}else{//如果该角色已经被授权，则从授权表中删除
				arg.put("uri", per.getUri());
				arg.put("rg_id", rp.getGroup_id());
				arg.put("rg", "G");
				argsDel.add(arg);
			}
		}		
		String[] order={"uri","rg_id","rg"};
		dao.updateMaps("addPermits", argsAdd, order);
		dao.updateMaps("delPermits", argsDel, order);
		return Message.OK;
	}
	
	@RequestMapping(value = "/users", method = RequestMethod.POST)
	@ResponseBody
	public Page<User> getUsers(int start,int size,String sort,String sortDirection){
		Page<User> users=dao.paginate(User.class, "users", start, size,sort,sortDirection, null);
		return users;
	}
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	@ResponseBody
	public Message addUser(@Valid User user,BindingResult result){
		String[] order={"user_id","user_name","password"};
		int  row=dao.updateObject("adduser", user, order);
		return Message.ADD_OK;
	}
	@RequestMapping(value = "/editUser", method = RequestMethod.POST)
	@ResponseBody
	public Message editUser(User user){
		String[] order={"user_name","password","user_id"};
		int  row=dao.updateObject("edituser", user, order);
		return Message.EDIT_OK;
	}
	@RequestMapping(value = "/delUser", method = RequestMethod.POST)
	@ResponseBody
	public Message delUser(String user_id){
		int  row=dao.update("deluser", user_id);
		return Message.DEL_OK;
	}
	@RequestMapping(value = "/getUserRoles", method = RequestMethod.POST)
	@ResponseBody
	public Page<RolePermit> getUserRoles(int start,int size,String sort,String sortDirection,String u){
		Page<RolePermit> rolePermits=dao.paginate(RolePermit.class, "userRole", start, size,sort,sortDirection, u);
		return rolePermits;
	}
	@RequestMapping(value = "/getUserGroups", method = RequestMethod.POST)
	@ResponseBody
	public Page<GroupPermit> getUserGroups(int start,int size,String sort,String sortDirection,String u){
		Page<GroupPermit> groupPermits=dao.paginate(GroupPermit.class, "userGroup", start, size,sort,sortDirection, u);
		return groupPermits;
	}
	
	@RequestMapping(value = "/updateUserRoles", method = RequestMethod.POST)
	@ResponseBody
	public Message updateUserRoles(@RequestBody User user){
		List<Map<String,Object>> argsAdd=new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> argsDel=new ArrayList<Map<String,Object>>();
		//参数装配过程
		for (RolePermit rp : user.getRoles()) {
			Map<String,Object> arg=new HashMap<String, Object>();
			if("N".equals(rp.getPermit())){//如果该角色没有被授权，则插入到授权表中
				arg.put("user_id", user.getUser_id());
				arg.put("role_id", rp.getRole_id());
				argsAdd.add(arg);
			}else{//如果该角色已经被授权，则从授权表中删除
				arg.put("user_id", user.getUser_id());
				arg.put("role_id", rp.getRole_id());
				argsDel.add(arg);
			}
		}		
		String[] order={"user_id","role_id"};
		dao.updateMaps("addUserRole", argsAdd, order);
		dao.updateMaps("delUserRole", argsDel, order);
		return Message.OK;
	}
	@RequestMapping(value = "/updateUserGroups", method = RequestMethod.POST)
	@ResponseBody
	public Message updateUserGroups(@RequestBody User user){
		List<Map<String,Object>> argsAdd=new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> argsDel=new ArrayList<Map<String,Object>>();
		//参数装配过程
		for (GroupPermit rp : user.getGroups()) {
			Map<String,Object> arg=new HashMap<String, Object>();
			if("N".equals(rp.getPermit())){//如果该角色没有被授权，则插入到授权表中
				arg.put("user_id", user.getUser_id());
				arg.put("group_id", rp.getGroup_id());
				argsAdd.add(arg);
			}else{//如果该角色已经被授权，则从授权表中删除
				arg.put("user_id", user.getUser_id());
				arg.put("group_id", rp.getGroup_id());
				argsDel.add(arg);
			}
		}		
		String[] order={"user_id","group_id"};
		dao.updateMaps("addUserGroup", argsAdd, order);
		dao.updateMaps("delUserGroup", argsDel, order);
		return Message.OK;
	}
	
	@RequestMapping(value = "/addCodeType", method = RequestMethod.POST)
	@ResponseBody
	public Message addCodeType(@Valid CodeType codeType,BindingResult result){
		String[] order={"dtid","dtname","remark"};
		int  row=dao.updateObject("addCodeType", codeType, order);
		return Message.ADD_OK;
	}
	@RequestMapping(value = "/editCodeType", method = RequestMethod.POST)
	@ResponseBody
	public Message editCodeType(@Valid CodeType codeType,BindingResult result){
		String[] order={"dtname","remark","dtid"};
		int  row=dao.updateObject("editCodeType", codeType, order);
		return Message.EDIT_OK;
	}
	@RequestMapping(value = "/delCodeType", method = RequestMethod.POST)
	@ResponseBody
	public Message delCodeType(@Valid CodeType codeType,BindingResult result){
		String[] order={"dtid"};
		int  row=dao.updateObject("delCodeType", codeType, order);
		return Message.DEL_OK;
	}
	@RequestMapping(value = "/getCodeTypes", method = RequestMethod.POST)
	@ResponseBody
	public Page<CodeType> getCodeTypes(int start,int size,String sort,String sortDirection,String u){
		Page<CodeType> codeTypes=dao.paginate(CodeType.class, "codeTypes", start, size,sort,sortDirection, null);
		return codeTypes;
	}
	@RequestMapping(value = "/addCode", method = RequestMethod.POST)
	@ResponseBody
	public Message addCode(@Valid Code code,BindingResult result){
		String[] order={"did","dname","dtid","pdid"};
		int  row=dao.updateObject("addCode", code, order);
		return Message.ADD_OK;
	}
	
	@RequestMapping(value = "/delCode", method = RequestMethod.POST)
	@ResponseBody
	public Message delCode(@Valid Code code,BindingResult result){
		String[] order={"did","dtid"};
		int  row=dao.updateObject("delCode", code, order);
		return Message.DEL_OK;
	}
	
	@RequestMapping(value = "/getCodes", method = RequestMethod.POST)
	@ResponseBody
	public Page<Code> getCodes(int start,int size,String sort,String sortDirection,String dtid){
		Page<Code> codes=dao.paginate(Code.class, "codes", start, size,sort,sortDirection, dtid);
		return codes;
	}
	@RequestMapping(value = "/refreshCache", method = RequestMethod.POST)
	@ResponseBody
	public List<Code> refreshCache(){
		//通过一个sql查询出字典类型表和字典表的关联集合
		List<Code> codes=dao.queryObjectList("allCodes",Code.class);
		//TODO refresh cache of the dictionary data  当前只考虑前端缓存，以后再考察是否有保留在内存的必要
		return codes;
	}
	@RequestMapping(value = "/getLogs", method = RequestMethod.POST)
	@ResponseBody
	public Page<AccessLog> getLogs(int start,int size,String sort,String sortDirection,String jsonLog){
		AccessLog log=JSON.parseObject(jsonLog, AccessLog.class);
		Page<AccessLog> logs=dao.paginate(AccessLog.class, log.select(), start, size,sort,sortDirection, log.args());
		System.out.println(log);
		return logs;
	}
}
